package com.mycjj.android.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mycjj.android.ProjectDataManage;
import com.mycjj.android.R;
import com.mycjj.android.adapter.TAdapter;
import com.mycjj.android.adapter.TreeViewAdapter;
import com.mycjj.android.bean.StoreCar;
import com.mycjj.android.bean.StoreCarSlowBaseBean;
import com.mycjj.android.bean.StoreCarSlowBaseBean.StoreCarSlowBean;
import com.mycjj.android.bean.TreeElement;
import com.mycjj.android.http.ProjectHttpRequestImpl;
import com.mycjj.android.http.ProjectHttpRequestInterface;
import com.mycjj.android.util.Preferences;
import com.mycjj.android.widget.TreeView;
import com.mycjj.android.widget.TreeView.LastLevelItemClickListener;

public class CarBrandActivity extends BaseActivity implements OnItemClickListener{
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_car_brand);
		initHeader();
		init();
		initData();
	}

	private ImageView mHeaderLeftImageview;
	private Button mHeaderRightButton;
	private TextView mHeaderTitleTextView;

	private void initHeader() {
		mHeaderLeftImageview = (ImageView) findViewById(R.id.header_left_button);
		mHeaderLeftImageview.setImageResource(R.drawable.back);
		mHeaderRightButton = (Button) findViewById(R.id.header_right_button);
		mHeaderRightButton.setVisibility(View.GONE);
		mHeaderTitleTextView = (TextView) findViewById(R.id.header_title_textview);
		mHeaderTitleTextView.setText("车辆品牌");
		mHeaderLeftImageview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CarBrandActivity.this.finish();
			}
		});
	}

	private TreeView treeView;
	private ListView listview;
	List<TreeElement> treeElements;
	static final int DATE_DIALOG_ID = 1;
	private int mYear;
	private int mMonth;
	private int mDay;
	private String carId,carName;
	private TreeElement element;
	@SuppressWarnings("unchecked")
	private void init() {
		Intent intent = getIntent();
		if (intent != null) {
			treeElements = (ArrayList<TreeElement>) intent
					.getSerializableExtra("treeElements");
		}

		treeView = (TreeView) findViewById(R.id.tree_view);
		LastLevelItemClickListener itemClickCallBack = new LastLevelItemClickListener() {// 创建节点点击事件监听

			@Override
			public void onLastLevelItemClick(int position,
					TreeViewAdapter adapter) {
				element = (TreeElement) adapter.getItem(position);
				getModelList(element.getBrandId());
			}
		};
		treeView.initData(CarBrandActivity.this, treeElements);// 初始化数据
		treeView.setLastLevelItemClickCallBack(itemClickCallBack);// 设置节点点击事件监听
		
		final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        
		listview = (ListView) findViewById(R.id.listview);
		listview.setOnItemClickListener(this);
		adapter = new CarModelAdapter(this);
		listview.setAdapter(adapter);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			DatePickerDialog picker = new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
			picker.setTitle("请选择车辆购买日期");
			return picker;
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			Log.e("mark", "year:"+year+";monthOfYear:"+monthOfYear+";dayOfMonth:"+dayOfMonth);
			element.setBrandId3(carId);
			dataManager.setElement(element);
			Preferences.setEditor(mApp, "carId", carId);//车辆id
			Preferences.setEditor(mApp, "carName", carName);//车辆id
			Preferences.setEditor(mApp, "buyCarDate", year+"-"+pad(monthOfYear+1)+"-"+pad(dayOfMonth));
			CarBrandActivity.this.finish();
		}
	};
	List<StoreCar> storeCarList;
	private void getModelList(String brandId) {
		request = new ProjectHttpRequestImpl(this, true);
		RequestParams params = new RequestParams();
		params.put("brand_father", brandId);
		params.put("page", "0");
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		params.put("token",
				Preferences.getSharedPreferences(this, "user_token", ""));
		request.requestStoreGetStoreCarSlowWithDoneHandler("", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						StoreCarSlowBaseBean baseBean = ProjectDataManage
								.getInstance().getStoreCarSlowBaseBean();
						if (baseBean != null) {
							if (baseBean.getCode() == 200) {
								StoreCarSlowBean slowBean = baseBean.getData();
								if (slowBean == null) {
									Toast.makeText(
											CarBrandActivity.this,
											"StoreCarSlowBean is null!return...",
											Toast.LENGTH_SHORT).show();
									Log.e("mark", "StoreCarSlowBean is empty!");
									return;
								}
								storeCarList = slowBean.getList();
								if (storeCarList != null
										&& storeCarList.size() > 0) {
									treeView.setVisibility(View.GONE);
									listview.setVisibility(View.VISIBLE);
									adapter.setList(storeCarList);
								} else {
									Log.e("mark",
											"slowBean.getList() is empty!!");
								}
							} else {
								Toast.makeText(
										CarBrandActivity.this,
										 baseBean.getMsg(),
										Toast.LENGTH_SHORT).show();
							}
						} else {
							Log.e("mark", "baseBean is empty!");
						}

					}
				});
	}
	
	  private static String pad(int c) {
	        if (c >= 10)
	            return String.valueOf(c);
	        else
	            return "0" + String.valueOf(c);
	    }

	private CarModelAdapter adapter;

	public class CarModelAdapter extends TAdapter<StoreCar> {

		public CarModelAdapter(Context mContext) {
			super(mContext);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.item_car_list_view, null);
				holder = new ViewHolder();
				holder.tv_name = (TextView) convertView
						.findViewById(R.id.tv_name);
				holder.pic = (ImageView) convertView
						.findViewById(R.id.header_pic);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			StoreCar bean = mList.get(position);
			imageLoader.displayImage(bean.getBrand_icon(), holder.pic);
			holder.tv_name.setText(bean.getBrand_name());
			return convertView;
		}

		class ViewHolder {
			TextView tv_name;
			ImageView pic;
		}
	}

	private void initData() {

	}

	@SuppressWarnings("deprecation")
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		StoreCar car = storeCarList.get(position);
		carId = car.getBrand_id();
		carName = car.getBrand_name();
		showDialog(DATE_DIALOG_ID);
	}

}
